package day52.basic.service.impl;

import day52.basic.commonenum.ErrorCode;
import day52.basic.config.RedisConfig;
import day52.basic.constants.Constant;
import day52.basic.domain.dto.SmsRegisteDto;
import day52.basic.exception.CustomException;
import day52.basic.service.IResetService;
import day52.basic.util.MD5Utils;
import day52.basic.util.StrUtils;
import day52.user.domain.Logininfo;
import day52.user.domain.User;
import day52.user.mapper.LogininfoMapper;
import day52.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ResetServiceImpl implements IResetService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    @Transactional
    public void resetUserPassword(SmsRegisteDto dto) {
        //检验两次密码是否一致
        if(!dto.getPassword().equals(dto.getConfirmPassword())){
            throw new CustomException(ErrorCode.PASSWORDS_INCONSISTENT.getCode());
        }
        //拼接短信验证码的key
        String smsKey = dto.getPhone() + Constant.REGISTER_KEY;
        //从redis中查询短信验证码
        String smsCodeValue = (String)redisTemplate.opsForValue().get(smsKey);
        //没有短信验证码则是过期了
        if(smsCodeValue == null){
            throw new CustomException(ErrorCode.SMSCODE_TIME_OUT.getCode());
        }
        //有短信验证码，校验
        String realCode = smsCodeValue.split(":")[0];
        if(!dto.getSmsCode().equals(realCode)){
            throw new CustomException(ErrorCode.SMSCODE_ERROR.getCode());
        }
        String phone = dto.getPhone();
        User user = userMapper.findByPhone(phone);
        if(user == null){
            throw new CustomException(ErrorCode.ACCOUNT_NOT_FOUND.getCode());
        }
        String salt = StrUtils.getComplexRandomString(32);
        String password = dto.getPassword();
        String pwd = MD5Utils.encrypByMd5(password + salt);
        user.setSalt(salt);
        user.setPassword(pwd);
        userMapper.update(user);
        Logininfo logininfo = logininfoMapper.findOne(user.getLogininfoId());
        logininfo.setSalt(salt);
        logininfo.setPassword(pwd);
        logininfoMapper.update(logininfo);
    }
}
